<?php
/*
	佣金管理
*/
defined('BY_JYA') or exit('error');
cfc('core')->checklogin();
$_RQ['op']=$_RQ['op']?$_RQ['op']:'list';
$tabs=array(
	array('op'=>'list','title'=>'佣金列表'),
	array('op'=>'balance','title'=>'申请结算'),
);
if($_RQ['op']=='list'){
	$params=array('uniacid'=>$_SESSION['uniacid']);
	$params['mid']=$_SESSION['uid'];
	if(isset($_RQ['status'])){
		$params['status']=intval($_RQ['status']);
		$return['params']['status']=$_RQ['status'];
	}
	$pindex = max(1, intval($_RQ['page']));
	$psize = 20;
	$total='';
	$parameter=array(
		'params'=>$params,
		'limit'=>array($pindex,$psize),
		'orderby'=>'id desc',
	);
	$list=$this->get_list('commission',$parameter,$total);
	$return['list']=$list;
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	$htmls=array(
		'type'=>'list',
		'tabs'=>array(
			array('op'=>'list','title'=>'佣金管理'),
			array('op'=>'balance','title'=>'申请结算'),
		),
		'list'=>array('data'=>'list','edit'=>false,'delall'=>false,'del_one'=>false,'list'=>array(
			array('name'=>'ordersn','title'=>'订单号','type'=>'string'),
			array('name'=>'type','title'=>'佣金类型','type'=>'radio','options'=>'types'),
			array('name'=>'fee','title'=>'金额','type'=>'string'),
			array('name'=>'status','title'=>'状态','type'=>'radio','options'=>'statuss'),
			array('name'=>'createtime','title'=>'产生时间','type'=>'time'),
			array('name'=>'balancesn','title'=>'结算单号','type'=>'string'),
		)),
		
	);
	if($_SESSION['os']=='windows'){
		$return['htmls']=$htmls;
	}
	$return['types']=array(
		'1'=>'省级代理分红',
		'2'=>'市级代理分红',
		'3'=>'县级代理分红',
	);
	$return['statuss']=array(
		'0'=>'订单待完成',
		'1'=>'待审核',
		'2'=>'待结算',
		'3'=>'已结算',
	);
	exi($return);
}
/*
	结算
	结算所有审核通过的佣金
*/
if($_RQ['op']=='balance'){
	/*
		生成结算单
		遍历指定用户所有已通过审核的佣金，生成结算单
	*/
	$commissions=$this->getall('commission',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid'],'status'=>2),array('id','fee'));
	if(!$commissions){
		exi('没有可结算的佣金！','error');
	}
	$fee=0;$num=0;$ids=array();
	foreach($commissions as $commission){
		$fee+=$commission['fee'];
		$num++;
		$ids[]=$commission['id'];
	}
	$new_balance=array(
		'uniacid'=>$_SESSION['uniacid'],
		'mid'=>$_SESSION['uid'],
		'commission_num'=>$num,
		'balancesn'=>get_ordersn('jy_move_agentcar','balancesn'),
		'fee'=>$fee,
		'createtime'=>TIMESTAMP,
		'status'=>0,
		
	);
	$this->insert('balance',$new_balance);
	pdo_update('commission',array('balancesn'=>$new_balance),array('id'=>$ids));
	exi('成功生成结算单！可以前往结算列表查看！');
}